// import styles from "@shared/confirm/styles/styles.module.less";
// import ReactDOM from "react-dom";
// import classNames from "classnames";
import styles from "@shared/confirm/styles/styles.module.less";
import ReactDOM from "react-dom";
import classNames from "classnames";
import { useCallback, useState, forwardRef, useImperativeHandle, useEffect } from "react";

interface Props {
  title?: string;
  content: string;
  onConfirm: () => void;
}

export interface confirmRef {
  close: () => void;
  open: () => void;
}

const Confirm = forwardRef<confirmRef, Props>(
    ({ title, content, onConfirm }, ref) => {
      const [isActive, setIsActive] = useState(false);
      const [visible, setVisible] = useState(false);
  
      // 控制弹框渲染
      const open = useCallback(() => {
        setVisible(true);
      }, [setVisible]);
  
      // 控制弹框销毁
      const close = useCallback(() => {
        setIsActive(false);
        setTimeout(() => {
          setVisible(false);
        }, 400);
      }, []);
  
      // 监听弹框渲染完成之后
      useEffect(() => {
        // 添加类名 执行动画
        if (visible) setIsActive(true);
      }, [visible, setIsActive]);
  
      // 将用于渲染和销毁弹框的方法挂载到 ref 对象中
      useImperativeHandle(ref, () => ({ open, close }), [open, close]);
      // 渲染视图
      return visible
        ? ReactDOM.createPortal(
            <div
              className={classNames(styles.layer, { [styles.active]: isActive })}
            >
              <div className={styles.container}>
                <div className={styles.title}>{title || "温馨提示"}</div>
                <div className={styles.content}>{content}</div>
                <div className={styles.buttons}>
                  <button className={styles.cancel} onClick={close}>
                    取消
                  </button>
                  <button className={styles.sure} onClick={onConfirm}>
                    确定
                  </button>
                </div>
              </div>
            </div>,
            document.body
          )
        : null;
    }
  );
  
  export default Confirm;
  
